package com.tcxhb.job.core.schedule.workflow;

import com.tcxhb.job.dao.dataobject.JobMachineDO;
import com.tcxhb.job.common.model.MiscResult;
import com.tcxhb.job.common.model.job.RunStrategy;
import com.tcxhb.job.core.constants.enums.DistStrategyEnum;
import com.tcxhb.job.core.schedule.execute.JobRunContext;
import com.tcxhb.job.core.schedule.router.RouterRandom;
import com.tcxhb.job.core.service.job.JobMachineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/12
 */
@Component
public class ShardingRouteFlow implements FlowHandler<JobRunContext> {
    @Autowired
    private JobMachineService jobMachineService;
    @Autowired
    private RouterRandom randomRouter;

    @Override
    public MiscResult handle(JobRunContext cxt) {
        // 获取有效的机器列表
        List<JobMachineDO> machineList = jobMachineService.getOnlineByCache(cxt.getAppName());
        if (machineList == null) {
            machineList = new ArrayList<>();
        }
        //计算分配数量
        Integer shardingNum = getShardingNum(cxt, machineList);
        //随机策略
        List<JobMachineDO> list = randomRouter.random(shardingNum, machineList);
        //分片数量
        cxt.setMachineList(list);
        cxt.setShardingNum(shardingNum);
        return MiscResult.suc();
    }

    private Integer getShardingNum(JobRunContext cxt, List<JobMachineDO> machineList) {
        RunStrategy strategy = cxt.getRunStrategy();
        Integer shardingNum = strategy.getShardingNum();
        //
        if (DistStrategyEnum.single.eq(strategy.getDistStrategy())) {
            shardingNum = 1;
        }
        if (DistStrategyEnum.all_board.eq(strategy.getDistStrategy())) {
            shardingNum = machineList.size();
        }
        return shardingNum;
    }
}
